/*
* File: serverTest.cpp
* Copyright (c) 2010. Silviu Caragea <silviu@intelliproject.net>
* Created on October 14, 2010, 2:42 PM
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*  1.Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
*  2.Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*  3.All advertising materials mentioning features or use of this software
*    must display the following acknowledgement:
*       This product includes software developed by the University of
*       California, Berkeley and its contributors.
*  4.Neither the name of the University nor the names of its contributors
*    may be used to endorse or promote products derived from this software
*    without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <sys/socket.h>
#include <sys/time.h>
#include "base/CFdEventMonitor-Inl.h"
#include "utils/sigslot.h"
#include "utils/CSocket-Inl.h"

// -lxnet

using namespace litevent;
using namespace litevent::util;

CFdEventMonitor *evMonitor = NULL;

void clientReadHandler(int fd, void *ctx, int revents);
void serverAcceptHandler(int fd, void *ctx, int revents);
void removeClient(CSocket client);

void removeClient(CSocket *clientSocket)
{
     CLogger::sharedLogger()->WriteFormated(" Client: %d disconnected", clientSocket->getSocket());
     evMonitor->RemoveEventWatcher(clientSocket->getSocket());
     /*clientSocket->Close();*/
     delete clientSocket;
}

void serverAcceptHandler(int fd, void *ctx, int revents)
{
    CLogger::sharedLogger()->WriteFormated("serverAcceptHandler event received:%d", revents);

    CSocket *serverSocket = (CSocket*)ctx;
    CSocket *clientSocket = serverSocket->Accept();

    if(clientSocket)
    {
        char szClientAddress[INET_ADDRSTRLEN];
        unsigned int port;
        clientSocket->GetRemoteIP(szClientAddress);
        clientSocket->GetRemotePort(port);

        CLogger::sharedLogger()->WriteFormated("Client connected from address:%s on port:%d",szClientAddress,port);
        clientSocket->MakeSocketNonBlock();
        evMonitor->SetEventWatcher(clientSocket->getSocket(),clientReadHandler,(void*)clientSocket, FDEVENT_IN|FDEVENT_ERR | FDEVENT_HUP );
    }    
}

void clientReadHandler(int fd, void *ctx, int revents)
{
    CSocket *clientSocket = (CSocket*)ctx;

    if(revents & (FDEVENT_ERR | FDEVENT_HUP))
    {
        CLogger::sharedLogger()->WriteFormated(" Client: %d error : %d", clientSocket->getSocket(), revents);
        removeClient(clientSocket);
    }
    else if(revents & FDEVENT_IN)
    {
        /*@todo: catch exceptions here */
        int toread = clientSocket->countToRead();

        if(toread)
        {
            CLogger::sharedLogger()->WriteFormated("Client: %d must read:%d bytes event: %d", clientSocket->getSocket(), toread, revents);
            char buff[toread+1];
            toread = read(fd,buff,toread);
        }
        else
        {
            removeClient(clientSocket);
        }
    }
   

}

int main(int argc, char** argv)
{
    CLogger::sharedLogger()->openLog("log.txt", true);

    evMonitor = new CFdEventMonitor(EnumEventHandlerTypeUnset);

    if (evMonitor->isInitialised() == false)
    {
        CLogger::sharedLogger()->Write("Failed initialise CFdEventMonitor.\n");
        return 1;
    }
    
    CLogger::sharedLogger()->WriteFormated("Client monitor used method:%s\n", evMonitor->getCurrentMethod());
    
    CSocket *serverSocket = new CSocket(8080,0);
    serverSocket->MakeSocketNonBlock();

    evMonitor->SetEventWatcher(serverSocket->getSocket(),serverAcceptHandler,(void*)serverSocket, FDEVENT_IN|FDEVENT_ERR | FDEVENT_HUP);

    char szServerAddress[INET_ADDRSTRLEN];
    unsigned int port;
    serverSocket->GetLocalIP(szServerAddress);
    serverSocket->GetLocalPort(port);

    CLogger::sharedLogger()->WriteFormated("Server running on %s port: %d",szServerAddress,port);

    CLogger::sharedLogger()->Write("Wait connection...");

    evMonitor->Loop();

    /*free everything to avoid memory leaks in profiler*/
    
    if(serverSocket)    
        delete serverSocket;
        
    if(evMonitor)
        delete evMonitor;

    delete CLogger::sharedLogger();

    fprintf(stderr, "End\n");
    return 0;
}

